from base.request_new import RequestNew
from base.tools import NDict
from base.logcontrol import logger
from business.register.template.api_h5 import h5_template
from business.register.template.api_app import app_template
from config import base_url
from datetime import datetime
from business.cookiesgetter.getter import user_login

today = datetime.now().strftime("%Y_%m_%d")


def br_register(mobile, api_template, terminal):
    rn = RequestNew()
    req_list = api_template(mobile)
    _vars = NDict()

    for req in req_list:
        try:
            req_data_keys = req["data"].keys()
        except AttributeError:
            req_data_keys = {}
        same = _vars.keys() & req_data_keys
        if same:
            for key in same:
                req["data"].update({key: _vars[key]})
        res, get_vars = rn.request_auto(**req)
        _vars.update(get_vars)
        if _vars["toLogin"]:
            logger.warning(f"{mobile}已注册,执行登录\n")
            cookie = user_login(terminal=terminal, mobile=mobile)
            return {"id": cookie["br_s_uid"], "cookies": cookie}

    return _vars


def h5_register(mobile):
    r = br_register(mobile, h5_template, "h5")
    with open(f"{base_url}/business/register/h5/register_h5_{today}.txt", "a+") as f:
        f.write(f"{mobile}:{r.get('id')}\n")
    return r.get('id'), r.get("cookies")


def app_register(mobile):
    r = br_register(mobile, app_template, "app")
    with open(f"{base_url}/business/register/app/register_app_{today}.txt", "a+") as f:
        f.write(f"{mobile}:{r.get('id')}\n")
    return r.get('id')
